<template>
  <div style="margin-top: 30px"></div>
  <a-row>
    <a-col :span="5" :offset="1">
      <a-input-search
          style="width: 280px"
          v-model:value="searchValue"
          placeholder="请输入电子书名称"
          :loading="searchLoading"
          enter-button
          size="large"
          @search="search"
      />
    </a-col>
    <a-col :span="3" :offset="1">
      <a-button type="primary" size="large" @click="add">新增</a-button>
    </a-col>
  </a-row>
  <a-table :columns="columns"
           :data-source="ebooks"
           :row-key="record => record.id"
           :loading="loading"
           :pagination="false"
        >
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'cover'">
        <img class="cover" :src="record.cover" />
      </template>
      <template v-else-if="column.key === 'action'">
        <a-space>
          <router-link :to="'/admin/doc?ebookId=' + record.id" ><a-button type="primary">文档管理</a-button></router-link>

          <a-button type="primary" @click="edit(record)">编辑</a-button>
          <a-popconfirm title="确认要删除吗？" @confirm="remove(record.id)">
            <template #icon><question-circle-outlined style="color: red" /></template>
            <a-button type="primary" danger>删除</a-button>
          </a-popconfirm>
        </a-space>
      </template>
    </template>
    <template #footer>
      <a-config-provider :locale="zhCN">
        <a-pagination
            v-model:current="pagination.current"
            v-model:pageSize="pagination.pageSize"
            :pageSizeOptions="pagination.pageSizeOptions"
            :total="pagination.total"
            show-size-changer
            :hideOnSinglePage="true"
            :showLessItems="true"
            :show-total="total => `共 ${total} 条`"
            @change="onPageChange"
        />
      </a-config-provider>
    </template>
  </a-table>

  <!-- 新增 -->
  <a-modal v-model:visible="visible" :title="title" :footer="null" :maskClosable="false">
    <a-form :model="ebook"
            :rules="rules"
            ref="myForm"
            @finish="handleOk"
      >
      <a-form-item label="名称" name="name">
        <a-input v-model:value="ebook.name" placeholder="请输入电子书名称" />
      </a-form-item>
      <a-form-item label="分类" name="category">
        <a-cascader v-model:value="category"
                    :options="categorys"
                    :field-names="{ label: 'name', value: 'id', children: 'children' }"
                    placeholder="请选择分类"
                    @change="selectCategroy"
        />
      </a-form-item>
      <a-form-item label="描述" name="description">
        <a-input v-model:value="ebook.description" placeholder="请输入电子书描述" />
      </a-form-item>
      <a-form-item label="封面" name="cover">
        <a-input v-model:value="ebook.cover" placeholder="请输入电子书封面" />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" html-type="submit">提交</a-button>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script>
import { SmileOutlined, DownOutlined,QuestionCircleOutlined } from '@ant-design/icons-vue';
import { ref } from "vue";
import axios from "axios";
import zhCN from 'ant-design-vue/es/locale/zh_CN';

import {Form, message} from 'ant-design-vue';

const columns = [{
    title: '封面',
    key: 'cover',
    dataIndex: 'cover',
  },{
    dataIndex: 'name',
    key: 'name',
    title: "名称"
  }, {
    title: '分类一',
    dataIndex: 'category1Name',
    key: 'category1Id',
  }, {
    title: '分类二',
    dataIndex: 'category2Name',
    key: 'category2Id',
  },  {
    title: '文档数',
    dataIndex: 'docCount',
    key: 'docCount',
  }, {
    title: '阅读数',
    dataIndex: 'viewCount',
    key: 'viewCount',
  }, {
    title: '点赞数',
    dataIndex: 'voteCount',
    key: 'voteCount',
  }, {
    title: 'Action',
    key: 'action',
  }];


export default {
  name: "admin-ebook",
  components: {
    SmileOutlined,
    DownOutlined,
    QuestionCircleOutlined
  },
  setup() {
    // 初始化表格
    const ebooks = ref([]);
    const loading = ref(true);
    const pagination = ref({
      current: 1,
      pageSize: 2,
      pageSizeOptions: ['1', '2', '5', '10', '20']
    });
    // 分页插件函数
    const onPageChange = (page, pageSize) => {
      get();
    }

    // 获取表格数据
    const get = () => {
      const params = {
        current: pagination.value.current,
        pageSize: pagination.value.pageSize,
      }

      if (searchValue.value){
        params.name = searchValue.value
      }
      axios.get("/ebook/list", {params}).then( (res) => {
        let data = res.data;
        if (data.code == 200){
          loading.value = false;
          ebooks.value = data.data.list;
          pagination.value.total = parseInt(data.data.total);
          searchLoading.value = false;
        }
      });
    }

    // 新增
    const visible = ref(false);
    const title = ref('新增电子书');
    const ebook = ref({});
    const rules = {
      name: [{
        required: true,
        message: '请输入电子书名称',
        trigger: 'blur'
      }],
      // 省略校验规则
    };;


    const add = () => {
      title.value = "新增电子书";
      ebook.value = {};
      category.value = [];
      visible.value = true;
    }

    const edit = (record) => {
      title.value = "编辑电子书信息";
      ebook.value = JSON.parse(JSON.stringify(record));
      category.value = [ebook.value.category1Id, ebook.value.category2Id];
      visible.value = true;
    }

    const handleOk = (e) => {
      axios.post('/ebook', ebook.value).then( (res) => {
          if (res.data.code == 200){
            let msg = "保存成功";
            if (ebook.value.id){
              msg = "修改信息成功";
            }
            // 保存成功
            message.success(msg);

            // 表格数据的刷新， 回显
            get();

            // 清空表单数据
            ebook.value = {};
          } else {
            // 保存失败
            message.error(res.data.message);
          }
        visible.value = false;
      })
    }

    // 删除信息
    const remove = (id) => {
      axios.delete('/ebook/' + id).then((res) => {
        if (res.data.code == 200){
          message.success("删除成功");
          // 表格数据的刷新， 回显
          get();
        } else{
          message.error(res.data.message);
        }
      });
    }

    // 搜索
    const searchValue = ref("");
    const searchLoading = ref(false);

    const search = () =>{
      searchLoading.value = true;
      get();
    }

    // 分类的多级选择
    const category = ref();

    const categorys = ref([]);

    // 获取 tree 格式的分类数据
    const getCategorys = () => {
      axios.get("/category/all").then( (res) => {
        let data = res.data;
        if (data.code == 200){
          categorys.value = data.data;
        }
      });
    }

    // 选择 分类后
    const selectCategroy = (value, selectedOptions) =>{
      ebook.value.category1Id = value[0];
      ebook.value.category2Id = value[1];
    }

    return {
      ebooks,
      columns,
      get,
      loading,
      pagination,
      onPageChange,
      zhCN,
      visible,
      title,
      add,
      ebook,
      rules,
      handleOk,
      edit,
      remove,
      searchValue,
      searchLoading,
      search,
      category,
      categorys,
      getCategorys,
      selectCategroy
    };
  },
  mounted() {
    // 获取表格数据
    this.get();
    // 获取分类数据
    this.getCategorys();
  }
}
</script>

<style scoped>
.cover{
  width: 80px;
  height: 80px;
}
</style>